extends IBasicComponent


@export var is_random_born: bool = true

@export var tilemaplayer: TileMapLayer = null
@export var born_factory: INodeFactory = null
@export var enemy_factory: INodeFactory = null


func __check_exports() -> Dictionary:
    return IComponent.merge({
        "tilemaplayer": func(): return tilemaplayer != null,
        "born_factory": func(): return born_factory != null,
        "enemy_factory": func(): return enemy_factory != null,
    }, super.__check_exports())

func born() -> void:
    var b: Node2D = born_factory.create()
    if is_random_born:
        var cell: Vector2 = tilemaplayer.get_used_cells().pick_random()
        var tile_size: Vector2 = tilemaplayer.tile_set.tile_size
        b.position = cell * tile_size + 0.5 * tile_size
    else:
        b.position = b.get_global_mouse_position()

    b.display()
    b.event_finished.connect(spawn_enemy)

func spawn_enemy(node: Node2D) -> void:
    var enemy: CharacterBody2D_Unit = enemy_factory.create()
    enemy.position = node.position
    enemy.event_finished.connect(destory_enemy)
    enemy.is_enable = true

    node.event_finished.disconnect(spawn_enemy)
    born_factory.destroy(node)

func destory_enemy(enemy: CharacterBody2D_Unit) -> void:
    enemy.is_enable = false
    enemy.event_finished.disconnect(destory_enemy)
    enemy_factory.destroy(enemy)
